package com.xs.mvc.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xs.mvc.exception.BusinessExcetion;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @Title: <P>GlobalExceptionHandler.java</P>
 * @Package <P>com.xs.mvc.handler</P>
 * @Description: <P>全局异常处理类，controller层如果没有处理默认会走这个异常</P>
 * @author renweiping
 * @date 2019年1月30日 下午6:09:45
 * @version 1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler extends BaseGlobalExceptionHandler {
	 //比如404的异常就会被这个方法捕获
    @ExceptionHandler(NoHandlerFoundException.class)    
    @ResponseStatus(HttpStatus.NOT_FOUND)    
     public ModelAndView handle404Error(HttpServletRequest req, HttpServletResponse rsp, Exception e) throws Exception {    
           return handleError(req, rsp, e, "error", HttpStatus.NOT_FOUND);    
     }    
    
    //500的异常会被这个方法捕获
    @ExceptionHandler(Exception.class)      
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 
    public ModelAndView handleError(HttpServletRequest req, HttpServletResponse rsp, Exception e) throws Exception { 
           return handleError(req, rsp, e, "error", HttpStatus.INTERNAL_SERVER_ERROR);  
    }

    //业务异常捕获
    @ExceptionHandler(BusinessExcetion.class)
    @ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
    public ModelAndView handleBusinessError(HttpServletRequest req, HttpServletResponse rsp, Exception e) throws Exception {
        return handleError(req, rsp, e, "error", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    public Logger getLogger() {
        return  Logger.getLogger(BaseGlobalExceptionHandler.class);
    }
}
